package com.monkey.controller;

import com.monkey.core.ErrorCode;
import com.monkey.core.WebRet;
import com.monkey.generator.model.TUserMonkey;
import com.monkey.model.comparator.MonkeyMySort;
import com.monkey.model.monkey.Monkey;
import com.monkey.model.monkey.MonkeyData;
import com.monkey.model.monkey.MonkeyDetailData;
import com.monkey.model.monkey.MonkeyOrder;
import com.monkey.model.synthesise.SynthesiseData;
import com.monkey.model.synthesise.SynthesisePreviewData;
import com.monkey.model.user.User;
import com.monkey.model.user.UserData;
import com.monkey.service.FeedService;
import com.monkey.service.MonkeyService;
import com.monkey.service.SynthesiseService;
import com.monkey.service.UserService;
import com.monkey.util.HelpUtil;
import com.monkey.util.WebConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * desc:
 * auth: chenxiaobin
 * data: 2018/1/10.
 */
@RestController
@RequestMapping(value = "/monkey")
public class MonkeyController {
    private static Logger logger = LoggerFactory.getLogger(MonkeyController.class);

    @Resource
	private HelpUtil helpUtil = null;
    
    @Resource
    private UserService userService = null;

    @Resource
    private MonkeyService monkeyService = null;

    @Resource
    private FeedService feedService = null;
    
    @Resource
    private SynthesiseService synthesiseService = null;
    
    @Resource
    private WebConfig webConfig = null;

    /**
     * 获取玩家的宠物
     *
     * @param p       bool 收益(true从小到大，false从大到小，未选中就不传)
     * @param g       bool 代数(true从小到大，false从大到小，未选中就不传)
     * @param w       bool 体重(true从小到大，false从大到小，未选中就不传)
     * @param gr      bool 成长(true从小到大，false从大到小，未选中就不传)
     * @param r       bool 生育(true从小到大，false从大到小，未选中就不传)
     * @param b       bool 掘金(true从小到大，false从大到小，未选中就不传)
     * @param userId  int 可选，非空非0表示查询指定玩家
     * @param status  int 宠物状态，0全部，1正常，2交易中，3生育中
     * @param offset  int 偏移量
     * @param num     int 数量
     * @param element int 宠物五行，-1全部，[0-5]
     * @return list 宠物列表
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public Map<String, Object> getList(@RequestBody Map<String, Object> params, @RequestHeader String token) {
        Map<String, Object> ret = new HashMap<>();
        if (null == token || token.isEmpty()) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        UserData user = userService.getInfo(token);
        if (null == user) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        int profit = 0;
        int bonus = 0;
        int generation = 0;
        int weight = 0;
        int grow = 0;
        int reproduct = 0;
        if (params.containsKey("b")) {
        	profit = ((boolean) params.get("b")) ? 1 : -1;
        }
        if (params.containsKey("p")) {
            bonus = ((boolean) params.get("p")) ? 1 : -1;
        }
        if (params.containsKey("g")) {
            generation = ((boolean) params.get("g")) ? 1 : -1;
        }
        if (params.containsKey("w")) {
            weight = ((boolean) params.get("w")) ? 1 : -1;
        }
        if (params.containsKey("gr")) {
        	grow = ((boolean) params.get("gr")) ? 1 : -1;
        }
        if (params.containsKey("r")) {
        	reproduct = ((boolean) params.get("r")) ? 1 : -1;
        }
        int userId = (int) params.getOrDefault("userId", user.getId());
        int offset = (int) params.get("offset");
        int num = (int) params.get("num");
        int status = (int) params.getOrDefault("status", 0);
        int element = (int) params.getOrDefault("element", -1);
        if (0 > offset || 0 > num) {
            ret.put("code", ErrorCode.PARAM_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.PARAM_ERROR));
            return ret;
        }
        offset = (offset - 1) * num;
        List<MonkeyData> monkeys = monkeyService.getList(userId, new MonkeyMySort(profit, bonus, generation, weight, grow, reproduct, offset, num), status,element);
        ret.put("code", ErrorCode.SUCCESS);
        ret.put("msg", "");
        ret.put("list", monkeys);
        ret.put("name", user.getName());
        ret.put("wallet", user.getWallet());
        return ret;
    }

    /**
     * 获取宠物详细信息
     *
     * @param id int 宠物id
     * @return info 宠物信息
     */
    @RequestMapping(value = "/getDetail", method = RequestMethod.POST)
    public Map<String, Object> getDetail_log(@RequestBody Map<String, Object> params, @RequestHeader String token) {
        Map<String, Object> ret = new HashMap<>();
        if (null == token || token.isEmpty()) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        UserData user = userService.getInfo(token);
        if (null == user) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        int monkeyId = (int) params.get("id");
        if (0 == monkeyId) {
            ret.put("code", ErrorCode.PARAM_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.PARAM_ERROR));
            return ret;
        }

        MonkeyDetailData monkey = monkeyService.getMonkeyDetail(user.getId(), monkeyId);
        if (null == monkey) {
            ret.put("code", ErrorCode.GET_DATA_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.GET_DATA_ERROR));
            return ret;
        }

        ret.put("code", ErrorCode.SUCCESS);
        ret.put("msg", "");
        ret.put("info", monkey);
        return ret;
    }

    /**
     * 获取宠物历史
     *
     * @param status int 状态：1买入，2卖出
     * @param offset int 偏移
     * @param num    int 数量
     * @return list 宠物列表
     */
    @RequestMapping(value = "/getOrderList", method = RequestMethod.POST)
    public Map<String, Object> getOrderList_log(@RequestBody Map<String, Object> params, @RequestHeader String token) {
        Map<String, Object> ret = new HashMap<>();
        if (null == token || token.isEmpty()) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        UserData user = userService.getInfo(token);
        if (null == user) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        int status = (int) params.get("status");
        int offset = (int) params.get("offset");
        int num = (int) params.get("num");
        if (0 > offset || 0 > num) {
            ret.put("code", ErrorCode.PARAM_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.PARAM_ERROR));
            return ret;
        }
        offset = (offset - 1) * num;
        List<MonkeyOrder> monkeys = monkeyService.getOrderList(user.getId(), status, offset, num);
        ret.put("code", ErrorCode.SUCCESS);
        ret.put("msg", "");
        ret.put("list", monkeys);
        return ret;
    }

    /**
     * 喂食
     *
     * @param id int 宠物id
     */
    @RequestMapping(value = "/feed", method = RequestMethod.POST)
    public Map<String, Object> feed_log(@RequestBody Map<String, Object> params, @RequestHeader String token) {
        Map<String, Object> ret = new HashMap<>();
        if (null == token || token.isEmpty()) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        User user = userService.getUserWithToken(token);
        if (null == user) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        int monkeyId = (int) params.get("id");
        int price = (int) params.get("price");
        if (0 == monkeyId) {
            ret.put("code", ErrorCode.PARAM_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.PARAM_ERROR));
            return ret;
        }

        //
        WebRet ret1 = feedService.feed(user, monkeyId, price);
        ret.put("code", ret1.getCode());
        ret.put("msg", ret1.getMsg());
        return ret;
    }
    
    /**
     * 宠物合成界面信息
     *
     * @param id int 主宠物id
     * @param strIds String 副宠物id 用','分割
     */
    @RequestMapping(value = "/getSynthesiseInfo", method = RequestMethod.POST)
    public Map<String, Object> getSynthesiseInfo(@RequestBody Map<String, Object> params, @RequestHeader String token) {
    	Map<String, Object> ret = new HashMap<>();
        if (null == token || token.isEmpty()) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        User user = userService.getUserWithToken(token);
        if (null == user) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        
        // 主宠Id
        int monkeyId = (int) params.get("id");
        // 副宠Id
        String strIds = (String) params.get("strIds");
        // 预览信息
        List<Integer> monkeyIds = helpUtil.splitToIntegerList(strIds, ",");
        SynthesisePreviewData monkeyPreviewData = synthesiseService.SynthesisePreview(user, monkeyId, monkeyIds);
        
        int price = webConfig.getInt("synthesise.gold");; // 合成花费狗头金
        int luckyLimit = webConfig.getInt("synthesise.lucky.limit"); // 幸运值上限
        int lucky = user.getLucky(); // 当前幸运值
        
        ret.put("code", ErrorCode.SUCCESS);
        ret.put("msg", "");
        ret.put("price", price);
        ret.put("lucky", lucky);
        ret.put("luckyLimit", luckyLimit);
        ret.put("gold", user.getGold());
        ret.put("preview", monkeyPreviewData);
        return ret;
    }
    
    /**
     * 宠物合成
     *
     * @param id int 主宠物id
     * @param strIds String 副宠物id 用','分割
     */
    @RequestMapping(value = "/synthesise", method = RequestMethod.POST)
    public Map<String, Object> synthesise(@RequestBody Map<String, Object> params, @RequestHeader String token) {
    	Map<String, Object> ret = new HashMap<>();
        if (null == token || token.isEmpty()) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        User user = userService.getUserWithToken(token);
        if (null == user) {
            ret.put("code", ErrorCode.TOKEN_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.TOKEN_ERROR));
            return ret;
        }
        
        // 主宠Id
        int monkeyId = (int) params.get("id");
        // 副宠Id
        String strIds = (String) params.get("strIds");
        List<Integer> monkeyIds = helpUtil.splitToIntegerList(strIds, ",");
        
        // 验证Id是否重复
        List<Integer> checkList = new ArrayList<Integer>(monkeyIds);
        checkList.add(monkeyId);
        if(helpUtil.cheakIsRepeat(checkList) == false){
        	 ret.put("code", ErrorCode.SYNTHESISE_ELEMENT_ERROR);
             ret.put("msg", ErrorCode.getMsg(ErrorCode.SYNTHESISE_ELEMENT_ERROR));
             return ret;
        }
        
        // 获取主宠(检测加载缓存)
        MonkeyDetailData monkeyMain = monkeyService.getMonkeyDetail(user.getId(), monkeyId);
        if (null == monkeyMain) {
            ret.put("code", ErrorCode.GET_DATA_ERROR);
            ret.put("msg", ErrorCode.getMsg(ErrorCode.GET_DATA_ERROR));
            return ret;
        }
        
        // 合成
        SynthesiseData synthesiseData = synthesiseService.synthesise(user, monkeyId, monkeyIds);
        ret.put("code", synthesiseData.getCode());
        ret.put("msg", synthesiseData.getMsg());
        ret.put("isGod", synthesiseData.getIsGod());
        ret.put("info", synthesiseData.getMonkey());
        ret.put("uuid", synthesiseData.getUuid());
        return ret;
    }
}
